<?php
/**
 * @Author: lianlianzan(13040@qq.com)
 * @Date:   2018-08-18 16:40:16
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2021-02-20 09:56:51
 */

namespace app\admin\controller;
use app\common\controller\Backend;

class WeixinApplet extends Backend {

	function initialize() {
		parent::initialize();
		$this->saveAndGetConfigIdentify('', '小程序管理', '', 'weixinxcx');

		$this->weixinAppletDao = model('weixin_manage/WeixinApplet');
	}

	public function index() {
		//获取列表
		$map = $parameter = array();

		$count = $this->weixinAppletDao->countSearch($map);
		$Page = new \org\util\PageBootstrap($count, config('app.per_page'), $parameter);
		$pageShow = $Page->show();
		list($list) = $this->weixinAppletDao->search($map, $Page->getLimit());
		//print_r($list);exit;
		$this->assign('count', $count);
		$this->assign('pageShow', $pageShow);
		$this->assign('list', $list);

		return $this->fetch();
	}

	public function add() {
		$id = input('param.id', '', 'intval');

		if ($id) {
			$info = $this->weixinAppletDao->getInfo($id);
		}
		$this->assign('id', $id);
		$this->assign('info', $info);

		return $this->fetch();
	}

	public function doAdd() {
		$id = input('post.id', '', 'intval');
		$data = input('post.data/a', '', 'pwEscape');

		if ($id) {
			$info = $this->weixinAppletDao->get($id);
		}

		if (!$data['wxnumber']) {
			$this->error('请输入微信号');
		}

		$uploadInfo = $this->comuploadFile('weixin', 'ewmurl', $info['ewmurl']);
		$uploadInfo && $data['ewmurl'] = $uploadInfo['saveFullPath'];

		//验证数据
		//$this->validateData($data, 'ManageGroup.edit');

		if ($id) {
			$result = $this->weixinAppletDao->baseUpdateData($id, $data);
			if ($result !== false) {
				$this->createCert($data);
				$this->success('保存成功', url('admin/weixinApplet/index'));
			} else {
				$this->error('保存失败'.showDbError($this->weixinAppletDao));
			}
		} else {
			$data['create_time'] = $this->ts;
			$result = $this->weixinAppletDao->baseAddData($data);
			if ($result !== false) {
				$this->createCert($data);
				$this->success('添加成功', url('admin/weixinApplet/index'));
			} else {
				$this->error('添加失败'.showDbError($this->weixinAppletDao));
			}
		}
	}

	public function doDelete() {
		$id = input('param.id', '', 'intval');

		$result = $this->weixinAppletDao->del($id);
		if ($result !== false) {
			$this->success('删除成功', url('admin/weixinApplet/index'));
		} else {
			$this->error('删除失败'.showDbError($this->weixinAppletDao));
		}
	}

	public function createCert($weixinAccountInfo) {
		$savePath = CMF_ROOT.'data/'.$weixinAccountInfo['wxnumber'].'/';
    	if (!is_dir($savePath)) {
	    	mkdir($savePath);
	    }
		$fp = fopen($savePath.'apiclient_cert.pem', "w");
		fwrite($fp, $weixinAccountInfo['apiclient_cert']);
		fclose($fp);
		$fp = fopen($savePath.'apiclient_key.pem', "w");
		fwrite($fp, $weixinAccountInfo['apiclient_key']);
		fclose($fp);
	}

}